package com.javaweb.controller;

import com.javaweb.controller.common.ResponseResult;
import com.javaweb.controller.common.TokenManager;
import com.javaweb.model.User;
import com.javaweb.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

import static com.javaweb.common.BusinessConstants.TOKEN_KEY;
import static com.javaweb.common.BusinessConstants.USER_KEY;

/**
 * @desc:
 * @author: Ping
 * @date: 2024/10/21 22:14
 */

@Controller
@RequestMapping("/user")
@Slf4j
@Validated
public class UserController {

    @Autowired
    private UserService userService ;

    @PostMapping("/login")
    @ResponseBody
    public ResponseResult<String> login(HttpServletRequest request,
                                        @NotBlank @RequestParam String username,
                                        @NotBlank @RequestParam  String password)  {

        log.info(" username: {}, password: {}",username,password);
        User user = userService.login(username, password);
        if (ObjectUtils.isEmpty(user)) {
            return ResponseResult.error(HttpStatus.OK,
                    "用户名或密码错误");
        }
        // session 中存储user
        HttpSession session = request.getSession() ;
        session.setAttribute(USER_KEY, user.getName()) ;
        String token = TokenManager.getToken(user) ;
        session.setAttribute(TOKEN_KEY,token);
        return ResponseResult.ok(token,"登录成功");
    }

    @PostMapping("/login/json")
    @ResponseBody
    public ResponseResult<String> login(HttpServletRequest request,
                                @Validated @RequestBody User user)  {
        return this.login(request,user.getName(),user.getPassword()) ;
    }





}
